package com.wgts.wgts.mvp.view.activity.main;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationManagerCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.viewpage.ComFragmentAdapter;
import com.wgts.wgts.control.viewpage.NoScrollViewPager;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerMainActivityComponent;
import com.wgts.wgts.dagger.module.MainActivityModule;
import com.wgts.wgts.mvp.presenter.IMainActivityPersenter;
import com.wgts.wgts.mvp.view.IMainActivityView;
import com.wgts.wgts.mvp.view.activity.classification.ClassificationFragment;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.mycenter.MyCenterFragment;
import com.wgts.wgts.mvp.view.activity.shopkeeper.ShopKeepFragment;
import com.wgts.wgts.mvp.view.activity.shopkeeper.UpgradeShopKeeperFragment;
import com.wgts.wgts.mvp.view.activity.tasklobby.WgtsWgtsTaskLobbyFragment;
import com.wgts.wgts.mvp.view.activity.wgtshome.WgtsHomePageFragment;
import com.wgts.wgts.mvp.view.callback.IHomePageActivityCallbackFragment;
import com.wgts.wgts.mvp.view.callback.IHomePageContentFragmentCallBackActivity;
import com.wgts.wgts.mvp.view.fragment.HomePageFragment;
import com.wgts.wgts.mvp.view.activity.shopCar.ShoppingCarFragment;
import com.wgts.wgts.netmodle.resp.AppUpdateEntity;
import com.wgts.wgts.netmodle.resp.UserInfoEntity;
import com.wgts.wgts.netmodle.resp.VipMessageEntity;
import com.wgts.wgts.react.MD5Util;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.InstallUtil;
import com.wgts.wgts.tools.MoHuGlide;
import com.wgts.wgts.tools.UpdateDialogFragment;
import com.wgts.wgts.tools.VipMessageDate;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MoHuMainActivity extends BaseActivity implements IMainActivityView,
        IHomePageContentFragmentCallBackActivity, ChangeViewPageCallBack, HomePageFragment.HomePageFragmentToMohuMainActivity {
    @BindView(R.id.img_home)
    ImageView imgHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.linear_home)
    LinearLayout linearHome;
    @BindView(R.id.img_vip)
    ImageView imgVip;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.linear_vip)
    LinearLayout linearVip;
    @BindView(R.id.img_shop)
    ImageView imgShop;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.linear_shop)
    LinearLayout linearShop;
    @BindView(R.id.img_my)
    ImageView imgMy;
    @BindView(R.id.tv_my)
    TextView tvMy;
    @BindView(R.id.linear_my)
    LinearLayout linearMy;
    @BindView(R.id.tab_bottom)
    LinearLayout tabBottom;
    @BindView(R.id.viewpage)
    NoScrollViewPager viewpage;
    @BindView(R.id.img_class)
    ImageView imgClass;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.linear_class)
    LinearLayout linearClass;
    private long exitTime = 0;
    public static final String MainType = "mainType";
    public static final String PAY_RESULT = "payResult";

    private InstallUtil mInstallUtil;


    private ArrayList<Fragment> fragments;

    private ArrayList<IHomePageActivityCallbackFragment> hidemagicIndicators;

    @Inject
    IMainActivityPersenter persenter;

    public WgtsHomePageFragment fragment;

    @Override
    public void init() {
        DaggerMainActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .mainActivityModule(new MainActivityModule(this))
                .build()
                .inject(this);


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus){
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus){
            //initView();
        }
    }


    @Override
    public void onCreate(Bundle saveInstanceBundle) {
        super.onCreate(saveInstanceBundle);
        setContentView(R.layout.home_page_activity);
        ButterKnife.bind(this);
        setSwipeBackEnable(false); //禁止滑动删除
        persenter.userInfo();
        //initView();
        updateInfo();
        initButtonTabal();
    }




    private void initView() {
        NotificationManagerCompat.from(this).areNotificationsEnabled();
        fragments = new ArrayList<>();
        fragment = new WgtsHomePageFragment();
        ShoppingCarFragment carFragment = new ShoppingCarFragment();
        UpgradeShopKeeperFragment upgradeShopKeeperFragment = new UpgradeShopKeeperFragment();
        ShopKeepFragment shopKeepFragment = new ShopKeepFragment();
        MyCenterFragment myCenterFragment = new MyCenterFragment();
        ClassificationFragment classificationFragment = new ClassificationFragment();
        WgtsWgtsTaskLobbyFragment taskLobbyFragment = new WgtsWgtsTaskLobbyFragment();

        fragments.add(fragment);
        fragments.add(upgradeShopKeeperFragment);
        fragments.add(taskLobbyFragment);
        fragments.add(myCenterFragment);
//        hidemagicIndicators = new ArrayList<>();
//        hidemagicIndicators.add(fragment);
        //hidemagicIndicators.add(fragment1);

        //persenter.vipMessage();
        viewpage.setScanScroll(false);
        viewpage.setAdapter(new ComFragmentAdapter(getSupportFragmentManager(), fragments));
        viewpage.setOffscreenPageLimit(fragments.size());

        onClickHome();



    }

    private void initButtonTabal() {
    }

    @OnClick({R.id.linear_vip, R.id.linear_shop, R.id.linear_my, R.id.linear_home, R.id.linear_class})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.linear_vip:
                onClickeVip();
                break;
            case R.id.linear_shop:
                onClickShopCar();
                break;
            case R.id.linear_my:
                onClickMy();
                break;
            case R.id.linear_home:
                onClickHome();
                break;
            case R.id.linear_class:
                clickClass();
                break;

        }
    }

    private void onClickHome(){
        initButtom();
        initText();
        MoHuGlide.getInstance().loadIconImg(this, "", imgHome, R.mipmap.icon_action_home_current);
        tvHome.setTextColor(getResources().getColor(R.color.crush_red));
        viewpage.setCurrentItem(0, false);

//        if(fragment != null){
//            fragment.checkList();
//        }
    }

    private void clickClass() {

    }

    @Override
    public void hideMagicIndicator() {
        for (int i = 0; i < hidemagicIndicators.size(); i++) {
            hidemagicIndicators.get(i).hideMagicIndicator();
        }
    }

    @Override
    public void showMagicIndicator() {
        for (int i = 0; i < hidemagicIndicators.size(); i++) {
            hidemagicIndicators.get(i).showMagicIndicator();
        }
    }

    private void initButtom() {
        MoHuGlide.getInstance().loadIconImg(this, "", imgHome, R.mipmap.icon_action_home);
        MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.icon_action_member);
        MoHuGlide.getInstance().loadIconImg(this, "", imgShop, R.mipmap.icon_action_task);
        MoHuGlide.getInstance().loadIconImg(this, "", imgMy, R.mipmap.icon_action_like);


    }

    private void initText() {
        tvHome.setTextColor(getResources().getColor(R.color.hint_6));
        tvNumber.setTextColor(getResources().getColor(R.color.hint_6));
        tvShop.setTextColor(getResources().getColor(R.color.hint_6));
        tvMy.setTextColor(getResources().getColor(R.color.hint_6));
        tvClass.setTextColor(getResources().getColor(R.color.hint_6));
    }


    @Override
    public void onError(int status, String msg) {
        if(status == 0xffff){
            initView();
        }
    }

    @Override
    public void vipMessage(List<VipMessageEntity> vipMessageEntitys) {
        VipMessageDate.getInstance().setList(vipMessageEntitys);
    }

    @Override
    public void userInfoResult(UserInfoEntity entity) {
        if(entity == null){
            Intent intent = new Intent(MoHuMainActivity.this, LoginActivity.class);
            startActivity(intent);
        }

        initView();
    }

    @Override
    public void appUpdate(AppUpdateEntity entity) {

        String path = Environment.getExternalStorageDirectory() + "/WgtsDownFiles/" + MD5Util.encrypt(entity.url) + ".apk";

        mInstallUtil = InstallUtil.getInstance(this, path);

        UpdateDialogFragment updateDialogFragment;

        updateDialogFragment = UpdateDialogFragment.setToastMessage(entity);

        UpdateDialogFragment.setmInstallUtil(mInstallUtil);

        if(entity.forceUpgrade == 1){

            updateDialogFragment.show(getSupportFragmentManager(), "");

        }else{
            if(entity.upgrade == 1){

                updateDialogFragment.show(getSupportFragmentManager(), "");
            }
        }


    }

    private void onClickMy() {
        if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
            initButtom();
            initText();
            MoHuGlide.getInstance().loadIconImg(this, "", imgMy, R.mipmap.icon_action_like_current);
            tvMy.setTextColor(getResources().getColor(R.color.crush_red));
            viewpage.setCurrentItem(3, false);
        } else {
            Intent intent = new Intent(MoHuMainActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    }

    private void onClickShopCar() {
        initButtom();
        initText();
        MoHuGlide.getInstance().loadIconImg(this, "", imgShop, R.mipmap.icon_action_task_current);
        tvShop.setTextColor(getResources().getColor(R.color.crush_red));
        //linearTitle.setVisibility(View.GONE);
        viewpage.setCurrentItem(2, false);
    }

    private void onClickeVip() {


        initButtom();
        initText();
        viewpage.setCurrentItem(1, false);
        MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.icon_action_member_current);
        tvNumber.setTextColor(getResources().getColor(R.color.crush_red));

//        if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
//
//            if(AppInfor.getInstance().getUserState() > 1){
//                MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.ic_shop_bar_cur);
//            }else{
//                MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.ic_action_member_cur);
//            }
//            if (AppInfor.getInstance().getUserState() > 1) {
//                viewpage.setCurrentItem(5, false);
//            } else {
//                viewpage.setCurrentItem(2, false);
//            }
//
//        } else {
//            Intent intent = new Intent(MoHuMainActivity.this, LoginActivity.class);
//            startActivity(intent);
//        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void changeViewPage(int position) {
        initButtom();
        initText();
        viewpage.setCurrentItem(position, false);
        MoHuGlide.getInstance().loadIconImg(this, "", imgHome, R.mipmap.icon_action_home_current);
        tvHome.setTextColor(getResources().getColor(R.color.crush_red));
    }

    public void logOut(){
        viewpage.removeAllViews();
        initView();
    }

    private void updateInfo(){
        PackageManager manager = this.getPackageManager();
        String name = null;
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        name = info.versionName;
        persenter.appUpdate("", name);
    }



    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        payResult(intent.getIntExtra(PAY_RESULT, 0));
        updateInfo();
        //UpdateSuccess();
    }


    @Override
    public void refresh() {
        //persenter.vipMessage();
    }

    private void payResult(int type){
        switch (type){
            case 0:
                initButtom();
                initText();
                MoHuGlide.getInstance().loadIconImg(this, "", imgHome, R.mipmap.icon_action_home_current);
                tvHome.setTextColor(getResources().getColor(R.color.crush_red));
                viewpage.setCurrentItem(0, false);
                break;
            case 1:
                initButtom();
                initText();
                viewpage.setCurrentItem(1, false);
                MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.icon_action_member_current);
                tvNumber.setTextColor(getResources().getColor(R.color.crush_red));
                break;
        }
    }


    public void UpdateSuccess(){

//        if(fragment != null){
//            fragment.updateSuccess();
//        }

        persenter.userInfo();

//        initButtom();
//        initText();
//        MoHuGlide.getInstance().loadIconImg(this, "", imgHome, R.mipmap.icon_action_home_current);
//        tvHome.setTextColor(getResources().getColor(R.color.crush_red));
//        viewpage.setCurrentItem(0, false);

    }

    public void upLevel(){
        initButtom();
        initText();
        viewpage.setCurrentItem(1, false);
        MoHuGlide.getInstance().loadIconImg(this, "", imgVip, R.mipmap.icon_action_member_current);
        tvNumber.setTextColor(getResources().getColor(R.color.crush_red));
    }

    public void jsToVip(){
        viewpage.setCurrentItem(1, false);
    }

}
